<template>
    <div class="login-box">
      <h1>叩丁狼商品管理系统</h1>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="0"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="ruleForm.username"
            autocomplete="off"
            :prefix-icon="UserFilled"
            size="large"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            :prefix-icon="Lock"
            size="large"
            placeholder="请输入用密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script setup lang="ts">
  import { reactive, ref } from "vue";
  import { ElMessage, FormInstance } from "element-plus";
  import { UserFilled, Lock } from "@element-plus/icons-vue";
  import { user } from "@/api";
  import { useRouter } from "vue-router";
  import { useUserStore } from "@/store";
  
  const userStore = useUserStore();
  
  const router = useRouter();
  
  const ruleFormRef = ref<FormInstance>();
  
  // 自定义的规则是一个函数 ， rule - 规则 ， value - 输入框的值 , callback -
  const validatePass = (rule: any, value: string, callback: any) => {
    if (value === "") {
      // 如果不通过校验，需要 callback里面传入一个错误对象
      callback(new Error("密码不能为空"));
    } else {
      // 如果校验通过，就直接调用 callback就行
      callback();
    }
  };
  
  const ruleForm = reactive({
    username: "",
    password: "",
  });
  
  const rules = reactive({
    username: [
      
      { required: true, message: "用户名不能为空", trigger: "blur" },

    ],
    password: [{ validator: validatePass, trigger: "blur" }],
  });
  
  
  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    
    formEl.validate((valid) => {
      
      if (!valid) {
        return false;
      }
  
      
      user.loginApi(ruleForm).then((res) => {
        if (res.code === 200) {
          
          localStorage.setItem("token", res.data.tokenHead + res.data.token);
          
          ElMessage.success("登录成功");
         
          router.push("/index");
        }
      });
    });
  };
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };
  </script>
  
  <style lang="less" scoped>
  .login-box {
    width: 400px;
    margin: 150px auto 0;
    h1 {
      font-size: 32px;
      text-align: center;
    }
    .el-button {
      width: 100%;
    }
    :deep(.el-input__wrapper) {
      background-color: transparent;
    }
    :deep(.el-input__inner) {
      color: #fff;
    }
  }
  </style>